/*
 * DMServer.cpp
 *
 *  Created on: Aug 29, 2016
 *      Author: ubuntu
 */

#include <iostream>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <signal.h>
#include "Update.h"
#include "common.h"
#include "Conf.h"

using namespace std;

int prodaemon = 1;

Update *pUpdate = NULL;

static void parse_cmd(int argc, char **argv)
{
	int c;
	while ((c = getopt(argc, argv, "d:c:l:f")) != -1)
	{
		switch (c) {
		case 'd':
			if (optarg) {
				set_debuglevel(atoi(optarg));
			}
			break;
		case 'f':
			prodaemon = 0;
			break;
		case 'c':
			if (optarg) {
				SetConf(optarg);
			}
			break;
		case 'l':
			if (optarg) {
				set_logfile(optarg);
			}
			break;
		}
	}
}

void
sigchld_handler(int s)
{
	pid_t pid;
	int stat;

	while ((pid = waitpid(-1, &stat, WNOHANG)) > 0);
	return;
}

void termination_handler(int s)
{
	if (!pUpdate)
		exit(0);
	pUpdate->stop();
}

static void init_signal()
{
	struct sigaction sa;
	sa.sa_handler = sigchld_handler;
    sigemptyset(&sa.sa_mask);
	sa.sa_flags = SA_RESTART;
	if (sigaction(SIGCHLD, &sa, NULL) == -1) {
		debug(LOG_ERR, "sigaction(): %s", strerror(errno));
		exit(1);
	}

	sa.sa_handler = SIG_IGN;
	if (sigaction(SIGPIPE, &sa, NULL) == -1) {
		debug(LOG_ERR, "sigaction(): %s", strerror(errno));
		exit(1);
	}

	sa.sa_handler = termination_handler;
	sigemptyset(&sa.sa_mask);
	sa.sa_flags = SA_RESTART;

	if (sigaction(SIGTERM, &sa, NULL) == -1) {
		debug(LOG_ERR, "sigaction(): %s", strerror(errno));
		exit(1);
	}

	if (sigaction(SIGQUIT, &sa, NULL) == -1) {
		debug(LOG_ERR, "sigaction(): %s", strerror(errno));
		exit(1);
	}

	if (sigaction(SIGINT, &sa, NULL) == -1) {
		debug(LOG_ERR, "sigaction(): %s", strerror(errno));
		exit(1);
	}
}

static void main_func()
{
	pUpdate = new Update();
	if (pUpdate->init())
		pUpdate->start();
	delete pUpdate;
	pUpdate = NULL;
}

int main(int argc, char **argv)
{
	ConfInit();
	parse_cmd(argc, argv);
	ReadConf();
	init_signal();
	if (prodaemon)  {
		if (fork() == 0) {
			setsid();
			main_func();
		}
		exit(0);
	} else {
		main_func();
	}
	return 0;
}


